package com.khotyn.heresy.controller;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.khotyn.heresy.util.ValidateCodeGenerator;

/**
 * 生成验证码和验证码图片控制类，并负责将验证码放入会话中用于验证
 * 验证码请求url为validateCode.html，为了能够刷新验证吗，可在url后以参数的形式增加一串随机数
 * @author 金灵杰
 *
 */
@Controller
@RequestMapping("/validateCode.html")
public class ValidatorCodeController {
	/**
	 * 处理验证码请求，产生验证码图片(PNG格式)，并将对应验证码存入会话（session）中（键为validateCode）
	 * @param response 将验证码图片通过outputStream输出
	 * @param model 将验证码保存到会话中
	 */
	@RequestMapping
	public void generateValidateCode(HttpServletResponse response, HttpSession session)
	{
		ValidateCodeGenerator vcg = new ValidateCodeGenerator(30,50,4,30);
		vcg.generateValidateCode();
		String validateCode = vcg.getRandCode();		//获取验证码
		session.setAttribute("validateCode", validateCode);
		try {
			response.setContentType("image/png");		//设置http响应格式为png图片
			ImageIO.write(vcg.getImage(), "PNG", response.getOutputStream());		//将生成的图片通过response流输出
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
